﻿using Microsoft.Win32;
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace InPlainSightBasic
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnOpenNewImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = CreateOpenDialog("Image for embedding");

            if (dialog.ShowDialog() == true)
            {
                string fileName = dialog.FileName;
                txtOriginalImageSource.Text = fileName;
                imgOriginalImage.Source = new BitmapImage(new Uri(fileName, UriKind.Absolute));              
            }
        }

        private static OpenFileDialog CreateOpenDialog(string title)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.CheckFileExists = true;
            dialog.CheckPathExists = true;
            dialog.Multiselect = false;
            dialog.Title = title;
            dialog.DefaultExt = "*.png";
            dialog.Filter = "PNG Image Files (*.png) | *.png|Bitmap Image Files (*.bmp) | *.bmp";
            return dialog;
        }

        private static SaveFileDialog CreateSaveDialog()
        {
            SaveFileDialog dialog = new SaveFileDialog();            
            dialog.CheckPathExists = true;
            dialog.AddExtension = true;
            dialog.OverwritePrompt = true;
            dialog.DefaultExt = "*.png";
            dialog.Filter = "PNG Image Files (*.png) | *.png|Bitmap Image Files (*.bmp) | *.bmp";
            return dialog;
        }

        private void btnCreateMessage_Click(object sender, RoutedEventArgs e)
        {
            tcMain.SelectedIndex = 1;
        }

        private void btnEncryptInImage_Click(object sender, RoutedEventArgs e)
        {
            if (txtOriginalImageSource.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please select an image (png or gif) file to be used."); ;
                return;
            }

            if (!System.IO.File.Exists(txtOriginalImageSource.Text))
            {
                MessageBox.Show("The file does not exist.");
                return;
            }

            Bitmap img = new Bitmap(txtOriginalImageSource.Text);
            string text = txtOriginalMessage.Text;

            //Just in case the number of characters that make up the message is greater than
            //the width of the image
            int lines = text.Length / img.Width;

            for (int rowIdx = 0; rowIdx <= lines; rowIdx++)
            {
                for (int colIdx = 0; colIdx < text.Length; colIdx++)
                {
                    System.Drawing.Color pixel = img.GetPixel(colIdx, rowIdx);
                    char letter = text[colIdx];
                    int value = Convert.ToInt32(letter);
                    img.SetPixel(colIdx, rowIdx, System.Drawing.Color.FromArgb(pixel.R, pixel.G, value % 255));
                }
            }

            //Store the length of the embedded message in the last 'line' of the image
            string lengthStr = text.Length.ToString();

            //The first character will be the length of the length string as a byte
            System.Drawing.Color pix = img.GetPixel(0, img.Height - 1);
            img.SetPixel(0, img.Height - 1, System.Drawing.Color.FromArgb(pix.R, pix.G, lengthStr.Length));

            for (int index = 0; index < lengthStr.Length; index++)
            {
                System.Drawing.Color pixel = img.GetPixel(index + 1, img.Height - 1);
                img.SetPixel(index + 1, img.Height - 1, System.Drawing.Color.FromArgb(pixel.R, pixel.G, Convert.ToInt32(lengthStr[index])));
            }

            //Marker {|}
            pix = img.GetPixel(lengthStr.Length + 1, img.Height - 1);
            img.SetPixel(lengthStr.Length + 1, img.Height - 1, System.Drawing.Color.FromArgb(pix.R, pix.G, 123));

            pix = img.GetPixel(lengthStr.Length + 1, img.Height - 1);
            img.SetPixel(lengthStr.Length + 2, img.Height - 1, System.Drawing.Color.FromArgb(pix.R, pix.G, 124));

            pix = img.GetPixel(lengthStr.Length + 1, img.Height - 1);
            img.SetPixel(lengthStr.Length + 3, img.Height - 1, System.Drawing.Color.FromArgb(pix.R, pix.G, 125));

            var sfdEncryptedImage = CreateSaveDialog();
            if (sfdEncryptedImage.ShowDialog() == true)
            {
                img.Save(sfdEncryptedImage.FileName);
                txtOriginalMessage.Clear();                
                MessageBox.Show("The text has been embedded.", "Operation successful", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void btnDecryptMessage_Click(object sender, RoutedEventArgs e)
        {
            if (txtEncryptedImageSource.Text.Trim() == string.Empty)
            {
                MessageBox.Show("Please select an image (png or gif) file to be used.");
                return;
            }

            if (!System.IO.File.Exists(txtEncryptedImageSource.Text))
            {
                MessageBox.Show("The file does not exist.");
            }

            Bitmap img = new Bitmap(txtEncryptedImageSource.Text);

            System.Drawing.Color pixel = img.GetPixel(0, img.Height - 1);

            int length = pixel.B;
            string lengthStr = string.Empty;
            for (int index = 0; index < length + 3; index++) //3 represents the length of the marker
            {
                pixel = img.GetPixel(index + 1, img.Height - 1);
                char c = Convert.ToChar(pixel.B);
                string letter = System.Text.Encoding.ASCII.GetString(new byte[] { Convert.ToByte(c) });

                lengthStr = lengthStr + letter;
            }

            try
            {
                if (!lengthStr.Contains("{|}"))
                {
                    throw new Exception();
                }

                int msgLength = Convert.ToInt32(lengthStr.Substring(0, length));
                int lines = msgLength / img.Width;
                StringBuilder sb = new StringBuilder();

                for (int rowIdx = 0; rowIdx <= lines; rowIdx++)
                {
                    for (int colIdx = 0; colIdx < msgLength; colIdx++)
                    {
                        pixel = img.GetPixel(colIdx, rowIdx);
                        char c = Convert.ToChar(pixel.B);
                        string letter = System.Text.Encoding.ASCII.GetString(new byte[] { Convert.ToByte(c) });

                        sb.Append(letter);
                    }
                }

                txtOriginalMessage.Text = sb.ToString();                
                tcMain.SelectedIndex = 1;
                MessageBox.Show("Message has been revealed.", "Operation successful", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch
            {
                MessageBox.Show("Invalid image selected. This image does not contain any recognizable encoded information.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnOpenEncryptedImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = CreateOpenDialog("Image for decryption");

            if (dialog.ShowDialog() == true)
            {
                txtEncryptedImageSource.Text = dialog.FileName;
                imgEncryptedImage.Source = new BitmapImage(new Uri(dialog.FileName, UriKind.Absolute));
            }
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow form = new AboutWindow();
            form.Owner = this;
            form.ShowDialog();
        }
    }
}
